package utils.okhttp;

import lombok.Getter;
import okhttp3.*;
import org.jetbrains.annotations.NotNull;
import utils.aria2.Aria2Config;

import java.io.IOException;
import java.util.concurrent.TimeUnit;

@Getter
public class OkHTTPConfig {
    private final Aria2Config config = Aria2Config.getInstance();
    private final OkHttpClient client;
    private final String WSURL;
    private final String HTTPURL;

    private OkHTTPConfig() {
        OkHttpClient.Builder builder = new OkHttpClient.Builder();
        builder.readTimeout(10, TimeUnit.SECONDS);
        builder.writeTimeout(10, TimeUnit.SECONDS);
        builder.connectTimeout(30, TimeUnit.SECONDS);
//        builder.addInterceptor(new BasicAuthInterceptor("admin", "3565704748"));
        builder.retryOnConnectionFailure(true);
        client = builder.build();
        WSURL = "ws://" + config.getServerHost() + ":" + config.getServerPort() + "/jsonrpc";
        HTTPURL = "http://" + config.getServerHost() + ":" + config.getServerPort() + "/jsonrpc";
    }

    private static class BasicAuthInterceptor implements Interceptor {
        private final String credentials;


        public BasicAuthInterceptor(String user, String password) {
            this.credentials = Credentials.basic(user, password);
        }

        @NotNull
        @Override
        public Response intercept(Chain chain) throws IOException {
            Request request = chain.request();
            Request authenticatedRequest = request.newBuilder()
                    .header("Authorization", credentials).build();
            return chain.proceed(authenticatedRequest);
        }
    }

    private static final OkHTTPConfig instance = new OkHTTPConfig();

    public static OkHTTPConfig getInstance() {
        return instance;
    }

    public Request getWSRequest() {
        return new Request.Builder().get().url(WSURL).build();
    }
}
